package app1.rapidsquare.com.core;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.classes.User;

/**
 * Created by Hikmat on 05.09.2014.
 */
public class GooglePlus {

    private GoogleApiClient mGoogleApiClient;
    private Activity mActivity;
    private ConnectionResult mConnectionResult;
    private boolean mIntentInProgress;
    private boolean mSignInClicked;
    private boolean mIsProfile;
    private ILoadComplete mILoadComplete;

    public GooglePlus(Activity activity, boolean isProfile, ILoadComplete iLoadComplete) {
        mActivity = activity;
        mIsProfile = isProfile;
        mILoadComplete = iLoadComplete;
    }

    public void onCreate(Bundle savedInstanceState) {
        mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
                .addConnectionCallbacks(connectionCallBack)
                .addOnConnectionFailedListener(onConnectionFailedListener).addApi(Plus.API, null)
                .addScope(Plus.SCOPE_PLUS_PROFILE).build();
    }

    public void onResume() {
        mGoogleApiClient.connect();
    }

    public void onPause() {
    }

    public void onStop() {
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    public void onDestroy() {
    }

    public void onSaveInstanceState(Bundle outState) {
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Utility.GOOGLE_PLUS_REQUEST_CODE) {
            if (resultCode != mActivity.RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
    }

    public void RunGooglePlusLogin() {
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
            mSignInClicked = true;
            resolveSignInError();
        }
    }

    private void resolveSignInError() {
        if (mConnectionResult != null && mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(mActivity, Utility.GOOGLE_PLUS_REQUEST_CODE);
            } catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        } else
            mGoogleApiClient.connect();
    }

    private GoogleApiClient.ConnectionCallbacks connectionCallBack = new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(Bundle bundle) {
            mSignInClicked = false;
            getProfileInformation();
        }

        @Override
        public void onConnectionSuspended(int i) {
            mGoogleApiClient.connect();
        }
    };

    private GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            if (!connectionResult.hasResolution()) {
                GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), mActivity,
                        0).show();
                return;
            }
            if (!mIntentInProgress) {
                mConnectionResult = connectionResult;
                if (mSignInClicked) {
                    resolveSignInError();
                }
            }
        }
    };

    private void getProfileInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi
                        .getCurrentPerson(mGoogleApiClient);

                User user = new User();

                if (user != null && currentPerson != null && currentPerson.isPlusUser()) {
                    if (!mIsProfile) {
                        user.GooglePlusId = currentPerson.getId();
                        user.Email = Plus.AccountApi.getAccountName(mGoogleApiClient);
                        String personName = currentPerson.getDisplayName();
                        user.FirstName = personName.split(" ")[1];
                        user.LastName = personName.split(" ")[0];
                        user.ImageUrl = currentPerson.getImage().getUrl();
                        user.SocialType = Utility.SocialType.GooglePlus.value;
                        user.GooglePlusName = user.FirstName + " " + user.LastName;

                    } else {
                        user.GooglePlusId = currentPerson.getId();
                        String personName = currentPerson.getDisplayName();
                        user.GooglePlusName = personName.split(" ")[0] + " " + personName.split(" ")[1];
                    }

                    mILoadComplete.onLoadComplete(user);
                }
            }
        } catch (Exception e) {
            Utility.Log("get google plus profile information ", e);
        }


    }
}
